package org.ix.dynamicapis.configure;

import org.ix.dynamicapis.configure.models.*;
import org.ix.dynamicapis.configure.utils.*;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.session.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.jdbc.core.JdbcTemplate;
import org.xml.sax.SAXException;

import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;
import java.util.Date;
import java.util.List;

@Slf4j
public class ApiTemplate extends BaseApiTemplate {

    private ConfigModel config;

    public ApiTemplate(String getApisUrl, String system, RedisTemplate<String, Object> redisTemplate, ConfigModel config) throws Exception {
        super(getApisUrl, system, redisTemplate);
        this.config = config;
        log.info("正在刷新配置，数据源" + config.getDataSource());
        refresh(config.getDataSource(), null, null, null);
    }

    public ApiTemplate(String getApisUrl, String system, RedisTemplate<String, Object> redisTemplate, String dataSource
            , JdbcTemplate jdbcTemplate, Configuration configuration) throws Exception {
        this(getApisUrl, system, redisTemplate, new ConfigModel(dataSource, jdbcTemplate, configuration));
    }

    @Override
    void setCache(String dtaSource, List<ApiModel> apis) throws ParserConfigurationException, SAXException, IOException {

        if (apis != null && !apis.isEmpty()) {
            long timestamp = new Date().getTime();
            for (ApiModel api : apis) {
                String fullPath = ApiTemplateUtils.getFullPath(api.getVersion(), api.getTopic(), api.getApiPath());
                ApiSqlModel apiSqlModel = ApiTemplateUtils.getApiSqlModel(config, api, timestamp);
                super.mybatisSqlMap.put(fullPath, apiSqlModel);
            }
        }
    }

    @Override
    void delCache(String dataSource, String fullPath) {

        if (StringUtils.isBlank(fullPath)) {
            super.mybatisSqlMap.clear();
        } else {
            super.mybatisSqlMap.remove(fullPath);
        }
    }

    @Override
    ConfigModel getConfigByPath(String fullPath) {
        return config;
    }
}
